import json
import os
import time

import requests
from openai import OpenAI


class AiApi:
    def __init__(self, api_key, base_url, model):
        self.api_key = api_key
        self.base_url = base_url
        self.model = model
        # self.api_key2 = "gpustack_5d730f94bc76cdd4_a165ffb0001aa1f13101f90240c10c4d"
        # self.base_url2 = "http://172.16.0.246/v1-openai"
        # self.model2 = "qwen2.5-coder-0.5b-instruct"

    def send_aliyun_model(self, code_text):
        content = '分析以下代码，判断其中是否包含加密(encryption)、解密(decryption)、签名(signature)、验签操作(verification)，哈希（hash)并识别使用的算法。\n' \
                  '分析结果请严格按照以下JSON格式返回，具体要求如下：\n' \
                  '1. 算法识别结果只用用一个JSON格式描述。\n' \
                  'JSON格式如下：{{"encryption": "0/1", "decryption": "0/1", "signature": "0/1", "verification": "0/1","hash": "0/1" ' \
                  '"algorithm":"使用的算法","analysis":"代码块分析" \n' \
                  '2. 有使用加密、解密、签名、验签、哈希算法的值用1表示，如键值对："encryption": "1"，没有使用相关算法则用0，如："encryption": "0"。分析说明以及推理过程写在analysis的值中\n' \
                  '代码：\n{code_text}\n' \
                  '答案：'.format(code_text=code_text)

        client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            api_key=self.api_key,
            base_url=self.base_url,
        )
        completion = client.chat.completions.create(
            model=self.model,  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': content}
            ],
        )
        return completion.model_dump_json()

    def send_request(self, code_text):
        content = '分析以下代码，判断代码其中是否包含加密(encryption)、解密(decryption)、签名(signature)、验签操作(verification)，哈希（hash)相关算法并识别使用的算法。\n' \
                  '分析结果请严格按照以下JSON格式返回，具体要求如下：\n' \
                  '1. 算法识别结果用一句话描述。\n' \
                  'JSON格式如下：{{"encryption": 0, "decryption": 0, "signature": 0, "verification": 0,"hash": 0, "algorithm":"XXX" \n' \
                  '"使用的算法"}} \n' \
                  '2. 有使用加密、解密、签名和验签用1表示使用了相应算法,用0表示没用使用相应算法。\n' \
                  '代码：\n{code_text}\n' \
                  '答案：'.format(code_text=code_text)

        # 替换为你的 GPUStack API Key
        YOUR_GPUSTACK_API_KEY = 'gpustack_5d730f94bc76cdd4_a165ffb0001aa1f13101f90240c10c4d'

        url = 'http://172.16.0.246/v1-openai/chat/completions'
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {YOUR_GPUSTACK_API_KEY}'
        }
        data = {
            "seed": None,
            "stop": None,
            "temperature": 1,
            "top_p": 1,
            "max_tokens": 1024,
            "model": "qwen2.5-coder-7b-instruct",
            "messages": [{'role': 'user', 'content': content}]
        }

        response = requests.post(url, headers=headers, data=json.dumps(data))

        # 打印响应状态码和响应内容
        print(f'Status Code: {response.status_code}')
        print(f'Response Content: {response.text}')


if __name__ == '__main__':
    code_trunk = 'npublic static byte[] SM3HashMac(String text,String key){\n        //1.填充0至key,或者hashkey,使其长度为sm3分组长度\n        /** ' \
                 'BLOCK_LENGTHSM3分组长度 ,64个字节,512位*/\n        byte[] sm3_key;\n        byte[] structured_key=new byte[BLOCK_LENGTH];\n        ' \
                 'byte[] IPAD=new byte[BLOCK_LENGTH];\n        byte[] OPAD=new byte[BLOCK_LENGTH];\n        if(StringUtil.base64Decode(' \
                 'key).length>BLOCK_LENGTH){\n            sm3_key= sm3Hash(StringUtil.base64Decode(key));\n            System.arraycopy(sm3_key,' \
                 '0,structured_key,0,sm3_key.length);\n        }else {\n            System.arraycopy(StringUtil.base64Decode(key),0,' \
                 'structured_key,0,StringUtil.base64Decode(key).length);\n        }\n        //2.让处理之后的key 与ipad (分组长度的0x36)做异或运算\n        for(' \
                 'int i=0;i<BLOCK_LENGTH;i++){\n            IPAD[i]=0x36;\n            OPAD[i]=0x5c;\n        }\n        byte[] ipadkey=XOR(' \
                 'structured_key,IPAD);\n        //3.将2的结果与text拼接\n        int textLen=text.getBytes().length;\n        byte[] t3=new byte[' \
                 'BLOCK_LENGTH+textLen];\n        System.arraycopy(ipadkey,0,t3,0,ipadkey.length);\n        System.arraycopy(text.getBytes(),0,' \
                 't3,ipadkey.length,text.getBytes().length);\n        //4.将3的结果sm3 哈希\n        byte[] t4=sm3Hash(t3);\n        //5.让处理之后的key ' \
                 '与opad(分组长度的0x5c)做异或运算\n        byte[] opadkey=XOR(structured_key,OPAD);\n        //6.4的结果拼接在5之后\n        byte[] t6=new byte[' \
                 'BLOCK_LENGTH+t4.length];\n        System.arraycopy(opadkey,0,t6,0,opadkey.length);\n        System.arraycopy(t4,0,t6,' \
                 'opadkey.length,t4.length);\n        //7.对6做hash\n        return (sm3Hash(t6));\n    }\n'

    # print(code_trunk)
    api = AiApi("sk-d28deaf4639345b0be41f69b11bad5ab", "https://dashscope.aliyuncs.com/compatible-mode/v1", "qwen-plus")
    # start = time.time()
    res = api.send_aliyun_model(code_trunk)
    res = json.loads(res)
    print(res)
    # end = time.time()
    # print(end - start)
    #
    # res = api.send_request(code_trunk)
    # print(res)
